<template>
	<view class="container" v-if="isload" ref="productRef" :class="showmask ? '' : ''">
		<view class="carousel">
<!--			<swiper indicator-dots circular=true duration="400" v-if="goodDetail&& goodDetail.galleryList && goodDetail.galleryList.length">-->
<!--				<swiper-item class="swiper-item" v-for="(item,index) in goodDetail.galleryList" :key="index">-->
<!--					<view class="image-wrapper">-->
<!--						<image :src="item" class="loaded" mode="aspectFill"></image>-->
<!--					</view>-->
<!--				</swiper-item>-->
<!--			</swiper> v-else-if="goodDetail"-->
			<block>
				<image :src="goodDetail.promotion.goodsImg" class="image-wrapper" mode="aspectFill"></image>
			</block>

    </view>
    <view :class="{'advertising':true, 'finish': buyState == 2}">
      <img src="/static/images/xianshimiaosha@2x.png" alt="">
      <view class="countdown">
        {{buyState < 2 ? timeLeft : '已结束'}}
<!--        距结束： 12:00:00-->
      </view>
    </view>

		<view class="introduce-section">
			<text class="title">{{goodDetail.promotion.goodsName}}</text>
<!--			<view v-if="!goodDetail.isAvoid" class="price-box">-->
<!--				<text class="price">{{currentSku? currentSku.specPrice: goodDetail.shopPrice}}</text>-->
<!--        <text class="price-tip"> USDT</text>-->
<!--        <text class="m-price" v-if="goodDetail.marketPrice != goodDetail.shopPrice ">{{currentSku? currentSku.marketPrice: goodDetail.marketPrice}} USDT</text>-->
<!--				<text class="coupon-tip" v-if="currentSku">会员价：{{currentSku.shopVipPrice}}</text>-->
<!--        <view class="share-pos" @click="shareHandle">-->
<!--          <image  src="/static/icon/share.png"></image>-->
<!--        </view>-->
<!--      </view>-->
			<view class="price-box">
				<text class="price">￥{{ (currentSku? currentSku.seckillPrice: goodDetail.promotion.marketPrice)*catNum}}</text>
        <text class="price-tip"></text>
        <text class="m-price" v-if="goodDetail.shopPrice != goodDetail.promotion.marketPrice ">￥{{goodDetail.shopPrice}} </text>
        <view class="share-pos" @click="shareHandle">
          <image  src="/static/icon/share.png"></image>
        </view>
      </view>

			<view class="bot-row">
				<text v-if="goodDetail.isAvoid == 0">销量: {{ goodDetail.saleNum}}</text>
				<text v-if="goodDetail.isAvoid == 1">运费: {{ goodDetail.goodsFreight}}</text>
				<text>库存: {{currentSku? currentSku.specStock:goodDetail.goodsStock}}</text>
				<text>浏览量: {{goodDetail.visitNum}}</text>
			</view>
			<view class="score" v-if="goodDetail.discount">
				<text class='costScore'>{{goodDetail.discount.costScore}}</text>积分可兑换<text class="recharge">{{goodDetail.discount.reduceMoney}}</text>
			</view>
		</view>
		<specsList :specs="goodDetail.promotion.goodsSpecs.selector" @commitSelect="selectSpecs" v-if="goodDetail.promotion.goodsSpecs"></specsList>

		<view class="commentCell" v-if="goodDetail">
			<list-cell icon="icon-pinglun-copy" iconColor="#ee883b" title="商品评价" :tips="goodDetail.appraisesNum+''" @eventClick="toProductComment"></list-cell>
		</view>
		<view class="shopBox" v-if="shop" @click="toshoplist(shop.shopId)">
			<image :src="shop.shopImg" class="shopImg" mode="aspectFill"></image>
			<view class="shopContext">
				<view class="shopName">
					{{shop.shopName}}
				</view>
				<view class="shopAddress">
					门店地址：{{shop.shopAddress}}
				</view>
				<view class="shopRange">
					经验范围：
					<block v-for="(item,index) in shop.majorCateNames" :key="index">
						<text>{{item}}</text>
					</block>
				</view>
			</view>
		</view>


		<view class="detail-desc">
			<view class="d-header">
				<text>图文详情</text>
			</view>
			<rich-text class="richtext" :nodes="desc"></rich-text>
		</view>

		<!-- 底部操作菜单 v-if="goodDetail.isAppointment != 1 && goodDetail.isFreeAppointment != 1" -->
		<view class="page-bottom" style="display: flex;justify-content: space-between;padding: 0px 20rpx">
			<navigator url="/pages/index/index" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-xiatubiao--copy"></text>
				<text>首页</text>
			</navigator>
			<!-- <navigator url="/pages/cart/cart" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-gouwuche"></text>
				<text>购物车</text>
			</navigator> -->
			<!-- <view class="p-b-btn" :class="{active: favorite}" @click="toFavorite">
				<text class="yticon icon-shoucang"></text>
				<text>收藏</text>
			</view> -->

			<block>
				<view :class="btnColor" style="width: 40%;">
					<button type="primary" class="action-btn no-border buy-now-btn " @click="buy()">立即购买</button>
				</view>
			</block>

		</view>


		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<view class="a-t">
					<image :src="goodDetail.goodsImg"></image>
					<view class="right">
						<text class="price" >￥{{ (currentSku? currentSku.seckillPrice: goodDetail.promotion.marketPrice)*catNum}}</text>
						<text class="stock">库存：{{currentSku?currentSku.specStock:goodDetail.goodsStock}}</text>
						<text></text>
						<!-- <view class="selected" v-if="currentSku">
							已选：
							<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
								{{sItem.name}}
							</text>
						</view> -->
					</view>
				</view>
				<!-- <view v-for="(item,index) in specList" :key="index" v-if="goodDetail.promotion.goodsSpecs" class="attr-list">
					<text>{{item.name}}</text>
					<view class="item-list">
						<text v-for="(childItem, childIndex) in specChildList" v-if="childItem.pid === item.id" :key="childIndex" class="tit"
						 :class="{selected: childItem.selected}" @click="selectSpec(childIndex, childItem.pid)">
							{{childItem.name}}
						</text>
					</view>
				</view> -->
				<block v-if="goodDetail.promotion.goodsSpecs&& goodDetail.promotion.goodsSpecs.selector &&　goodDetail.promotion.goodsSpecs.selector.length">
					<specsList :specs="goodDetail.promotion.goodsSpecs.selector" @commitSelect="selectSpecs"></specsList>
				</block>

				<view class="numRow">
					<view class="myStep">
						<text class="yticon icon--jianhao" @click="numChange('ninus')"></text>
						<input type="number" @input="numInput" :value="catNum" />
						<text class="yticon icon-jia1" @click="numChange('plus')"></text>
					</view>
				</view>
				<button class="btn" @click="toggleSpec('addCat')">完成</button>
			</view>
		</view>
		<!-- 分享 -->
		 <share-poster
         ref="share"
         :qrcodeVal="qrcodeVal"
         :slogan="['这里的正品品牌只要“半价”？好运凑一凑就有啦～']"
     />
	</view>
</template>
<!-- <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
<script>
	eruda.init();
</script> -->
<script>
  import siteInfo from "@/siteInfo.js"
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniIcon from '@/components/uni-icons/uni-icons.vue'
	import listCell from '@/components/mix-list-cell'
	import specsList from "@/components/specsList/specsList.vue"
  import sharePoster from "@/components/share-poster.vue"
  export default {
		components: {
			uniPopup,
			specsList,
			uniIcon,
			listCell,
      sharePoster
		},
		data() {
			return {
				is_sq:0,
				desc: '',
				isgift: '',
				sharegoodsId: '',
				loginUserId: '',
				inviteUserId: '',
				shareimg: '',
				ptid: '',
				ptidstart: '',
				skuid: '',
				isAllStart: '',
				participantslist: [],
				scrollTop: 0,
				showmask: false,
				goodsId: 0,
				endPin: '2020/07/25,15:00',
				endText: '',
				countInterval: null,
				currentSku: null,
				goodDetail: null,
				buyIt: false,
				shop: null,
				specClass: 'none',
				specSelected: [],
				catNum: 1,
				favorite: true,
				type: 0,
				piners: [],
				isformorder: '',
				isload: false,
        seckill_time_id: 0,
        timeLeft: '距开始 00:00:00',
        clearTime: null,
        buyState: 0,
        spec_ids: '',
			};
		},
		onShow() {
			this.countDown()
		},
    destroy(){
      clearInterval(this.clearTime)
    },
		async onLoad(options) {
			let that = this;
			//接收传值,id里面放的是标题，因为测试数据并没写id
			this.goodsId = options.id;
			this.seckill_time_id = options.time_id;
			this.isgift = options.isgift
			this.isAllStart = options.isAllStart
			console.log(options)

			if (options.inviteUserId) {
				console.log('通过分享后的链接进来')
				this.inviteUserId = options.inviteUserId;
				this.onrecommend()
			}
			if(options.is_sq){
				this.is_sq = options.is_sq
			}
			this.loadDetail();
			//规格 默认选中第一条
			// this.specList.forEach(item => {
			// 	for (let cItem of this.specChildList) {
			// 		if (cItem.pid === item.id) {
			// 			this.$set(cItem, 'selected', true);
			// 			this.specSelected.push(cItem);
			// 			break; //forEach不能使用break
			// 		}
			// 	}
			// })
			// this.shareList = await this.$api.json('shareList');
		},
		onPageScroll(scrollTop) {
			this.scrollTop = scrollTop
		},
		onUnload() {
			clearInterval(this.countInterval)
		},
    onBackPress(e){
      uni.setStorageSync('goodsBack', 1)
    },
		onHide() {
			clearInterval(this.countInterval)
		},
		methods: {
		  // // 0 未开始 1 进行中 2 已结束 秒杀倒计时
      getTimeLeft(seckill_time_status, seckill_to_time){
        clearInterval(this.clearTime)
        let _time
        switch (seckill_time_status){
          case 0:
            this.clearTime = setInterval(()=>{
              this.timeLeft = `距开始 ${this.getTimeDown(seckill_to_time--)}`
            }, 1000)
            break;
          case 1:
            this.clearTime = setInterval(()=>{
              this.timeLeft = `距结束 ${this.getTimeDown(seckill_to_time--)}`
            }, 1000)
            break;
          case 2:
            this.timeLeft = '已结束';
            break;
        }
      },
      getTimeDown(surplus){
        // 时
        let hours =0, minute = 0 , second =0;
        if (surplus >= 3600){
          hours = Math.floor(surplus / 3600);
          // console.log('surplus / 3600========', (surplus / 3600));
          surplus -= hours*(3600);
        }
        if (surplus >= 60){
          minute = Math.floor(surplus / 60);
          second = surplus - minute*60;
        }else{
          second = surplus;
        }
        second = second.toFixed(0);
        if (second <= 0 && surplus<=0){
          this.loadDetail();
        }

        return (hours >= 10 ? hours : `0${hours}`)+':'+(minute >= 10 ? minute : `0${minute}`)+':'+(second >= 10 ? second : `0${second}`);
      },
			toshoplist(id) {
				uni.navigateTo({
					url: '/district/districtDetail/districtDetail?shopId=' + id
				})
			},
			toexchangeDetail(id){
				var shop_ = JSON.stringify(this.shop)
				uni.navigateTo({
					url: '/district/exchange/exchangeorder?goodsId=' + id + "&shop=" + shop_
				})
			},
			shareApp() {
				console.log('1')
				// uni.share({
				//     provider: 'weixin',
				//     scene: "WXSceneSession",
				//     type: 5,
				//     imageUrl: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/app/share-logo@3.png',
				//     title: '欢迎体验uniapp',
				//     miniProgram: {
				//         id: 'gh_abcdefg',
				//         path: 'pages/index/index',
				//         type: 0,
				//         webUrl: 'http://uniapp.dcloud.io'
				//     },
				//     success: ret => {
				//         console.log(JSON.stringify(ret));
				//     }
				// });

			},

			onrecommend() {
				//jilu\
			},

			maskchange(e) {
				let that = this;
				e.show == false ? that.showmask = false : that.showmask = true;
			},
			openGroupmaxk() {
				let that = this;
				// document.scrollTop = that.scrollTop
				that.$refs.popup.open()
				that.showmask = true;
			},
			countDown() {
				this.countInterval = setInterval(() => {
					let end = new Date(this.endPin)
					let now = new Date()
					if (end.getTime() > now.getTime()) {
						let minSec = parseInt((end.getTime() - now.getTime()) / 1000)
						let d = parseInt(minSec / (24 * 60 * 60))
						let h = parseInt(minSec / (60 * 60) % 24);
						let m = parseInt(minSec / 60 % 60);
						let s = parseInt(minSec % 60);
						if (d > 0) {
							this.endText = `${d}天${h}时${m}分${s}秒`
						} else {
							this.endText = `${h}时${m}分${s}秒`
						}

					}
				}, 1000)

			},
			toProductComment() {
				uni.navigateTo({
					url: '/subPackage/productComments/productComments?goodsId=' + this.goodDetail.goodsId
				})
			},
			cartNumChange(e) {
				// this.catNum = e.number
			},
			numInput(e) {
				let max = this.currentSku ? this.currentSku.specStock : this.goodDetail.goodsStock
				max = parseInt(max)
				let num = parseInt(e.detail.value)
				if (num > max) {
					this.catNum = max
				} else if (num <= 0) {
					this.catNum = 1
				} else {

					this.catNum = num
				}
			},
			numChange(type) {
				// if(this.isfree == 1){
				// 	this.$api.msg('该商品为免单只可购买1个')
				// 	return;
				// }
				let max = this.currentSku ? this.currentSku.specStock : this.goodDetail.goodsStock
				max = parseInt(max)
				let num = this.catNum

				if (type == 'plus') {
					num++
				} else {
					num--
				}
				if (num > max) {
					this.catNum = max
				} else if (num <= 0) {
					this.catNum = 1
				} else {

					this.catNum = num
				}
			},
			sku() {
				let arr = []
				this.currentSku = null
				this.goodDetail.promotion.goodsSpecs.selector.forEach(item => {
					item.items.forEach(spec => {
						if (spec.select) {
							arr.push(spec.itemId)
						}
					})
				})
        this.goodDetail.promotion.goodsSpecs.log
				if (arr.length == this.goodDetail.promotion.goodsSpecs.selector.length) {
					arr.sort()
					let key = arr.join(':')
          this.spec_ids = key;
          console.log(this.goodDetail.promotion.goodsSpecs.sku[key]);
          this.currentSku = this.goodDetail.promotion.goodsSpecs.sku[key]
				}
			},
			selectSpecs(selectObj) {
				this.skuid = selectObj.id;
				let fa = this.goodDetail.promotion.goodsSpecs.selector[selectObj.level]
				for (let i in fa.items) {
					let item = fa.items[i]
					if (item.itemId == selectObj.id) {
						item.select = true
					} else {
						item.select = false
					}
				}
				this.goodDetail.promotion.goodsSpecs.selector.splice(selectObj.level, fa)
				this.sku()
			},
			loadDetail() {
				// that.goodsId
				let that = this
				that.$Request.request('/api/seckill/goodsdetail', 'GET', {
					goodsId: that.goodsId,
          seckill_time_id: that.seckill_time_id
				}).then(res => {
          if (res.status === -1){
            that.$api.msg(res.msg)
            setTimeout(()=>uni.navigateBack(), 1200)
            return ;
          }
					if (res.data) {
						that.goodDetail = res.data.goods
						that.desc = res.data.goods.goodsDesc.replace(/\<img\s/gi,
							'<img style="max-width:100%;height:auto;display: block;" ')
						that.isload = true;
						that.shop = res.data.shop
						that.loginUserId = res.data.loginUserId
						that.piners = res.data.pintuan ? res.data.pintuan.userList : []
						that.participantslist = res.data.pintuan ? res.data.pintuan.pintuanStartList : []
						that.sharegoodsId = that.goodDetail.goodsId;
            const {seckill_time_status, seckill_to_time} = res.data.goods.promotion.seckillTime;
            this.buyState = seckill_time_status ;
						this.getTimeLeft(seckill_time_status, seckill_to_time);
					} else {
						that.$api.msg('获取商品数据出现异常')
						uni.navigateBack()
					}
				}).catch(err => {
					console.log(err)
				})
			},
			//规格弹窗开关
			toggleSpec(type) {
				if (this.specClass === 'show') {
					if (type == 'addCat') {
						let that = this
						let data = {}
						if (that.goodDetail.promotion.goodsSpecs == null || that.goodDetail.promotion.goodsSpecs.selector.length == 0) {
							data = {
								goodsId: that.goodDetail.goodsId,
								buyNum: that.catNum
							}
						} else {
							if (that.currentSku) {
								data = {
									goodsSpecId: that.currentSku.goodsSpecId,
									buyNum: that.catNum
								}
							} else if (!that.currentSku && that.goodDetail.promotion.goodsSpecs && that.goodDetail.promotion.goodsSpecs.selector.length != 0) {
								that.$api.msg('请选择规格！')
								return
							}
						}

						if (this.buyIt) {
							data.type = 1
						} else {
							data.type = 0
						}
						that.$Request.request('/api/cart/add', 'POST', data).then(res => {
							console.log(res)
							// return;
							if (res.status == 1) {
								if (res.msg && res.msg.cartId) {
									if (!that.buyIt) {
										that.$api.msg('加入购物车成功！')
									}
									setTimeout(() => {
										if (that.buyIt) {

										  let goodsSpecId = this.currentSku?.goodsSpecId || 0
                      if (this.currentSku && !goodsSpecId){
                        uni.showToast({
                          title: '请选择规格！',
                          duration: 2000
                        });
                        return ;
                      }
                      uni.navigateTo({
												url: `/pages/order/createSeckillOrder?goodsId=${this.goodsId}&seckill_time_id=${this.seckill_time_id}&spec_ids=${goodsSpecId}`
											})
										} else {
											uni.switchTab({
												url: '/pages/cart/cart'
											})
										}
										that.specClass = 'hide';
										setTimeout(() => {
											that.specClass = 'none';
										}, 250);
									}, 800)
								} else {
									that.$api.msg('加入购物车失败！')
									that.buyIt = false
									setTimeout(() => {
										that.specClass = 'hide';
										setTimeout(() => {
											that.specClass = 'none';
										}, 250);
									}, 800)
								}
							}

						}).catch(err => {
							console.log('err', err)
              uni.showToast({
                title: err?.msg || err,
                icon: 'none'
              })
							that.buyIt = false
						})
					} else {
						this.specClass = 'hide';
						this.buyIt = false
						setTimeout(() => {
							this.specClass = 'none';
						}, 250);
					}

				} else if (this.specClass === 'none') {
					this.specClass = 'show';
					this.buyIt = false
				}
			},
			backtoAppointment(id){
				uni.navigateTo({
					url:'/district/appointment/appointment?shopId='+id
				})
			},
			//分享
			share() {
				this.$refs.share.toggleMask();
			},
      shareHandle(){
        this.$refs.share.open();
      },
			//收藏
			toFavorite() {
				this.favorite = !this.favorite;
			},
			buy() {
        if (this.buyState != 1){
          uni.showToast({
            title: this.buyState < 2 ?'商品暂时不能抢购！': '商品活动已结束',
            icon: 'none'
          })
          return ;
        }
				this.toggleSpec()
				this.buyIt = true
				// uni.navigateTo({
				// 	url: `/pages/order/createOrder`
				// })
			},
			stopPrevent() {}
		},
    computed:{
      qrcodeVal(){
        return `${siteInfo.root}/static/app/index.html?v1&share=ymyx@gs@id`+this.goodsId
      },
      btnColor(){
        //
        let str = 'action-btn-group';
        str += (this.buyState == 1 ? '' :' hasNotStarted')

        return str;
      }
    }
	}
</script>
<style>

</style>
<style lang='scss'>
.hasNotStarted{
  background: #b6b4b4!important;
}
.finish{
  background: #c1bebd;
}
.advertising{
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 92rpx;
  background: #EE5B25;
  bottom: 0rpx;
  z-index: 999;
  padding: 10rpx;
  img{
    width: 190rpx;
    height: 43rpx;
    align-self: center;
    margin-left: 20rpx;
  }
  .countdown{
    align-self: center;
    margin-right: 20rpx;
    color: white;
  }

}
	.richtext {}

	.pervent {
		width: 100%;
		height: 100%;
		position: fixed;
		overflow: hidden;
	}

	.pinTitle uni-button,
	button {}

	.yqdoPin {
		color: #fff !important;
		background-color: #e02f25 !important;
		border-radius: 4px;
		margin: 0;
		width: 85px;
		font-size: 12px;
		height: 25px;
		line-height: 25px;
		margin: 0;
	}

	.ptsuccess {
		color: rgb(255, 255, 255);
		background-color: #027aff;
		border-radius: 10upx;
		width: 120upx;
		height: 40upx;
		line-height: 40upx;
		text-align: center;
		font-size: 18upx;
		margin-top: 10upx;
	}

	.ptfail {
		color: rgb(255, 255, 255);
		background-color: #e02f25;
		border-radius: 10upx;
		width: 120upx;
		height: 40upx;
		line-height: 40upx;
		text-align: center;
		font-size: 20upx;
		margin-top: 10upx;
	}

  .share-pos{
    float: right;
    image{
      width: 40upx; height: 40upx;
    }
  }
  .price-box{
    display: block!important;
  }
	@import './product.scss'
</style>
